<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>求x=2sinx的解</title>
</head>

<body>
  <h1>HTML5绘制二分搜索过程求x=2sinx的解.</h1>
  <p>用二分搜索算法求x=2sinx的所有根，设计出具体的程序，使之能够动态演示搜索过程。</p>
  <canvas id="myCanvas" width="1000" height="550">
    很抱歉，您的浏览器不支持html5画布功能，所以不能正常显示。亲，还是请换个浏览器试试吧。
  </canvas>
  <script type="text/javascript">
    var c = document.getElementById("myCanvas");
    var pen = c.getContext("2d");
    var sx = 500,
      sy = 275;
    pen.strokeStyle = "Black";
    pen.lineWidth = 2;
    //绘制x轴
    pen.moveTo(sx - 400, sy);
    pen.lineTo(sx + 400, sy); //x轴
    pen.moveTo(sx + 400, sy);
    pen.lineTo(sx + 400 - 10, sy - 10); //x轴小箭头
    pen.moveTo(sx + 400, sy);
    pen.lineTo(sx + 400 - 10, sy + 10); //x轴小箭头
    //绘制y轴
    pen.moveTo(sx, sy - 250);
    pen.lineTo(sx, sy + 250); //y轴
    pen.moveTo(sx, sy - 250);
    pen.lineTo(sx - 10, sy - 250 + 10); //y轴小箭头
    pen.moveTo(sx, sy - 250);
    pen.lineTo(sx + 10, sy - 250 + 10); //y轴小箭头
    pen.stroke();
    //绘制y=x
    pen.beginPath();
    pen.strokeStyle = "Yellow";
    pen.moveTo(sx - 250, sy + 250);
    pen.lineTo(sx + 250, sy - 250);
    pen.stroke();
    //绘制y=2sinx
    pen.beginPath();
    pen.strokeStyle = "Green";
    pen.moveTo(sx - Math.PI * 100, sy);
    for (var i = -100; i <= 100; i++) {
      pen.lineTo(sx + Math.PI * i, sy - Math.sin(i / 100.0 * Math.PI) * 200);
    }
    pen.stroke();

    //绘制二分搜索过程
    pen.strokeStyle = "Red";
    var l1 = 0,
      r1 = Math.PI;

    function f1() {
      if (r1 - l1 > 1e-3) {
        var mid = (l1 + r1) / 2.0;
        pen.beginPath();
        pen.moveTo(sx + mid * 100, sy - Math.sin(mid) * 200);
        pen.lineTo(sx + mid * 100, sy);
        pen.stroke();
        if (mid > 2.0 * Math.sin(mid)) r1 = mid;
        else l1 = mid;
        setTimeout("f1()", 1000);
      } else {
        var ans = (l1 + r1) / 2.0;
        pen.font = "italic 14px serif";
        pen.fillText(ans.toPrecision(5), sx + ans * 100 - 15, sy + 15);
      }
    }
    var l2 = -Math.PI,
      r2 = 0;

    function f2() {
      if (r2 - l2 > 1e-3) {
        var mid = (l2 + r2) / 2.0;
        pen.beginPath();
        pen.moveTo(sx + mid * 100, sy - Math.sin(mid) * 200);
        pen.lineTo(sx + mid * 100, sy);
        pen.stroke();
        if (mid > 2.0 * Math.sin(mid)) r2 = mid;
        else l2 = mid;
        setTimeout("f2()", 1000);
      } else {
        var ans = (l2 + r2) / 2.0;
        pen.font = "italic 14px serif";
        pen.fillText(ans.toPrecision(5), sx + ans * 100 - 15, sy - 10);
      }
    }
    setTimeout("f1()", 1000);
    setTimeout("f2()", 1000);
  </script>
</body>

</html>
